package com.chijun.mform.process.dapater;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.chijun.mform.R;
import com.chijun.mform.create.mode.FormApproveProcess;
import com.chijun.mform.create.mode.FormFieldOption;
import com.example.ccj.b.c.custom.MImageView;

import java.util.List;


/**
 * 多选项的选项展示
 * 2024年11月10日23:38:06
 */
public class ShowMutileOptionAdapter extends RecyclerView.Adapter<ShowMutileOptionAdapter.ViewHolder>{

    List<FormFieldOption> formFieldOptionList;
    boolean isCanDelete;
    /**
     * 字段类型数组
     *
     * @param fields 字段列表
     */
    public ShowMutileOptionAdapter(List<FormFieldOption> fields,boolean isCanDelete){
        this.formFieldOptionList = fields;
        this.isCanDelete = isCanDelete;

    }

    @NonNull
    @Override
    public ShowMutileOptionAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ShowMutileOptionAdapter.ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.adapater_show_mutilt_option, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ShowMutileOptionAdapter.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        FormFieldOption option = formFieldOptionList.get(position);
        holder.text.setText(option.content);

        if (isCanDelete) {
            holder.delete.setVisibility(View.VISIBLE);
            holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    notifyRemove(position);
                }
            });
        } else {
            holder.delete.setVisibility(View.GONE);
        }

    }

    /**
     * 删除节点
     * @param position 节点编号
     */
    private void notifyRemove(int position){
        FormFieldOption remove = formFieldOptionList.remove(position);
        notifyItemRemoved(position);
        //重新加载从删除位置往下的所有item，如果删除的是中间，自删除的位置到最后开始是做重新添加操作
        //避免下表越界等错误
        notifyItemRangeRemoved(position,getItemCount());
    }


    @Override
    public int getItemCount() {
        return formFieldOptionList == null ? 0 : formFieldOptionList.size();
    }

    public static class ViewHolder extends  RecyclerView.ViewHolder{
        private final TextView text;
        private final MImageView delete;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            text = itemView.findViewById(R.id.adapter_select_field_type_text);
            delete = itemView.findViewById(R.id.adapter_select_field_type_delete);

        }
    }


    public interface OptionChangeListener{
        void onAdd();
        void onDelete();
    }
}
